package com.cas.object;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class Common_tool {
	public static byte[] getBytes(short x)
    {
        return new byte[] { 
            (byte)(x >>> 8),
            (byte)x
            };
    }
    
    public static byte[] getBytes(int x)
    {
        return new byte[] {
           (byte)(x >>> 24),
           (byte)(x >>> 16),
           (byte)(x >>> 8),
           (byte)x
            };
    }
    
    public static short swap(short x)
    {
    	return (short)((x << 8) | ((x >> 8) & 0xff));
    }
    
    public static int swap(int x)
    {
    	return (int)((swap((short)x) << 16) | (swap((short)(x >> 16)) & 0xffff));
    }
    
    public static int byteArrayToInt(byte[] buf, int startIndex)
    {
        ByteBuffer byte_buf = ByteBuffer.allocate(4);
        final byte[] change = new byte[4];
        
        for (int i = 0; i < 4; i++)
        {
        	change[i] = buf[startIndex + i];
        }

        
        byte_buf = ByteBuffer.wrap(change);

        return byte_buf.getInt();
    }
    
    public static short byteArrayToShort(byte[] buf, int startIndex)
    {
        ByteBuffer byte_buf = ByteBuffer.allocate(2);
        final byte[] change = new byte[2];
        
        for (int i = 0; i < 2; i++)
        {
        	change[i] = buf[startIndex + i];
        }

        byte_buf = ByteBuffer.wrap(change);

        return byte_buf.getShort();
    }
    
    public static String padLeft(String s, int n)
    {
    	String strTemp = "";
    	
    	for (int i = 0; i < n - s.length(); i++)
    	{
    		strTemp += " ";
    	}
    	strTemp += s;

    	return strTemp;
    }
    
    public static byte getCheckSum(byte[] rSendBuf, int iLength, int iStart)
    {
        byte chRtn = 0x00;

        if (iStart >= iLength)
            return chRtn;

        for (int i = iStart; i < iLength; i++)
        {
            chRtn += rSendBuf[i];
        }
        return chRtn;
    }
    
    public static String convByteToString(byte[] buf, int start, int offset) throws UnsupportedEncodingException
    {
    	int nCheckEndPosition = offset;
    	
    	for (int i = start; i < start + offset; i++)
        {
            if (buf[i] == 0x00)
            {
                nCheckEndPosition = i - start;
                break;
            }
        }
    	
    	return new String(buf, start, nCheckEndPosition, "GBK");
    }
    
    public static int convUnsignedByte(byte x)
    {
        return (int)x&0xff;
    }
}
